package org.opens.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import org.opens.dao.ShiroPermissionDao;
import org.opens.dao.ShiroPermissionWithRoleDao;
import org.opens.dao.ShiroRoleDao;
import org.opens.dao.ShiroUserWithRoleDao;
import org.opens.entity.ShiroPermission;
import org.opens.entity.ShiroPermissionWithRole;
import org.opens.entity.ShiroRole;
import org.opens.service.ShiroPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class ShiroPermissionServiceImpl implements ShiroPermissionService {

    @Autowired
    private ShiroPermissionDao shiroPermissionDao;

    @Autowired
    private ShiroPermissionWithRoleDao shiroPermissionWithRoleDao;

    @Override
    public List<ShiroPermission> findByRoleIdIn(List<Integer> roleIds) {
        if (CollectionUtil.isEmpty(roleIds)) {
            return Collections.emptyList();
        }

        List<ShiroPermissionWithRole> permissionWithRoles = shiroPermissionWithRoleDao.findByRoleIdsIn(roleIds);
        List<ShiroPermission> permissions = Collections.emptyList();

        if (CollectionUtil.isNotEmpty(permissionWithRoles)) {
            Set<Integer> permissionIds = permissionWithRoles.stream().map(ShiroPermissionWithRole::getPermissionId).collect(Collectors.toSet());
            if (CollectionUtil.isNotEmpty(permissionIds)) {
                permissions = shiroPermissionDao.selectBatchIds(permissionIds);
            }
        }

        return permissions;
    }

    @Override
    public List<ShiroPermission> findByRoleIn(List<ShiroRole> roles) {
        if (CollectionUtil.isEmpty(roles)) {
            return Collections.emptyList();
        }

        return findByRoleIdIn(roles.stream().map(ShiroRole::getId).collect(Collectors.toList()));
    }
}
